<template>
  <div>
    <!-- 权限点数据展示 -->
    <!-- 1. show-checkbox 显示选择框
         2. default-expand-all 默认展开
        3. check-strictly  设置true，可以关闭父子关联 -->
    <el-tree
      ref="tree"
      :data="list"
      :props="{ label: 'name' }"
      default-expand-all
      show-checkbox
      check-strictly
      node-key="id"
    />
    <!-- 底部 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="$emit('close')">取消</el-button>
        <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { AssibnRolesId, getAssibnRoles } from '@/api/settings'
export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {

      list: []
    }
  },
  created() {
    // 获取所有权限列表
    this.loadPermissionList()
    // 获取当前角色所拥有的权限
    this.loadAssignRoles()
  },
  methods: {
    async loadPermissionList() {
      const res = await getPermissionList()
      this.list = tranListToTreeData(res.data)
    },
    // 根据ID获取角色详情
    async loadAssignRoles() {
      try {
        const res = await getAssibnRoles(this.id)
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (e) {
        console.log(e)
      }
    },
    async hSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      try {
        const res = await AssibnRolesId({ id: this.id, permIds })
        this.$message.success(res.message)
        this.$emit('close')
      } catch (e) {
        this.$message.error(e.message)
      }
    }
  }
}
</script>
